package com.zbec.mdrs.service;

import com.zbec.mdrs.constants.Constants;
import com.zbec.mdrs.entity.RecordEntity;
import com.zbec.mdrs.entity.discount.Discount;
import com.zbec.mdrs.entity.drafts.Drafts;
import com.zbec.mdrs.entity.entrustedLoan.EntrustedLoan;
import com.zbec.mdrs.entity.guarantee.Guarantee;
import com.zbec.mdrs.entity.loan.Loan;
import com.zbec.mdrs.repository.jpa.*;
import com.zbec.mdrs.util.ResourceUtils;
import com.zbec.mdrs.vo.ExportVo;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;
import java.util.UUID;

/**
 * Created by fxl on 2015/11/3.
 */
@Component
@Transactional
public class FileService {

    @Autowired
    private LoanDao loanDao;

    @Autowired
    private DiscountDao discountDao;

    @Autowired
    private GuaranteeDao guaranteeDao;

    @Autowired
    private DraftsDao draftsDao;

    @Autowired
    private EntrustedLoanDao entrustedLoanDao;

    @Autowired
    private LogsService logsService;

    @Autowired
    private SystemDictCacheService systemDictCacheService;

    public String exportExcel(ExportVo vo,String path,String userIp){
        String type=vo.getBusinessType();
        String recordStatus="";
        if(vo.getSjsj()!=null && vo.getSjsj()!=""){
            vo.setSjsj(vo.getSjsj().replace("-",""));
        }
        if(vo.getSkipInd()!= null && "Y".equals(vo.getSkipInd())){
            recordStatus=Constants.RECORD_STATUS_ADDEDSKIPED;
        }else {
            recordStatus=Constants.RECORD_STATUS_ADDED;
        }
        String[] name=vo.getName().split(",");
        switch (type){
            case Constants.BUSINESS_TYPE_LOAN :
                List<Loan> loanList=loanDao.findLoanForExport(vo.getSjsj(), recordStatus, vo.getExistError());
                return writeFile(loanList,name,path,type,userIp);
            case Constants.BUSINESS_TYPE_DISCOUNT :
                List<Discount> discountList=discountDao.findDiscountForExport(vo.getSjsj(), recordStatus, vo.getExistError());
                return writeFile(discountList,name,path,type,userIp);
            case Constants.BUSINESS_TYPE_DRAFTS :
                List<Drafts> draftsList=draftsDao.findDraftsForExport(vo.getSjsj(), recordStatus, vo.getExistError());
                return writeFile(draftsList,name,path,type,userIp);
            case Constants.BUSINESS_TYPE_ENTRUSTED_LOAN :
                List<EntrustedLoan> entrustedLoanList=entrustedLoanDao.findEntrustedLoanForExport(vo.getSjsj(), recordStatus, vo.getExistError());
                return writeFile(entrustedLoanList,name,path,type,userIp);
            case Constants.BUSINESS_TYPE_GUARANTEE :
                List<Guarantee> guaranteeList=guaranteeDao.findGuaranteeForExport(vo.getSjsj(), recordStatus, vo.getExistError());
                return writeFile(guaranteeList,name,path,type,userIp);
            default:
              break;
        }
        return "error";
    }
    private String writeFile(List<?> dataList,String[] name,String path,String type,String userIp) {
        Boolean flag=true;
        String fileName = UUID.randomUUID().toString();
        fileName=fileName.toLowerCase();
        String filePath = path + File.separator+ fileName
                + ".xls";
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }

        try {
            // 第一步，创建一个webbook，对应一个Excel文件
            HSSFWorkbook wb = new HSSFWorkbook();
            // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
            String sheetName= ResourceUtils.getLocaleString("logs.type."+type);
            HSSFSheet sheet = wb.createSheet(sheetName);
            // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
            HSSFRow row = sheet.createRow((int) 0);
            // 第四步，创建单元格，并设置值表头 设置表头居中
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

            if (name != null) {
                for (int i = 0; i < name.length; i++) {
                    HSSFCell cell = row.createCell(i);
                    String title=ResourceUtils.getLocaleString("label." + type+"."+name[i]);
                    cell.setCellValue(title);
                    cell.setCellStyle(style);
                }
            }

            Field f;
            // 下面是填充数据
            if (dataList != null && dataList.size() > 0) {
                for (int i = 0; i < dataList.size(); i++) {
                    row = sheet.createRow( i + 1);
                    for (int j = 0; j < name.length; j++) {
                        try {
                            f = dataList.get(i).getClass()
                                    .getDeclaredField(name[j]);
                        }catch (NoSuchFieldException e){
                           f=dataList.get(i).getClass().getSuperclass().getDeclaredField(name [j]);
                        }
                        f.setAccessible(true);
                        String value="";
                        if(f.getName().equals("bz")){
                            if(f.get(dataList.get(i))!=null) {
                                value = systemDictCacheService.findSysDictionaryCode(Constants.Constants_BZ, f.get(dataList.get(i)).toString(),Constants.DICTIONARY_DESC);
                            }
                        }else if(f.getName().equals("wjfl")){
                            if(f.get(dataList.get(i))!=null) {
                                value = systemDictCacheService.findSysDictionaryCode(Constants.Constants_WJFL, f.get(dataList.get(i)).toString(),Constants.DICTIONARY_DESC);
                            }
                        }else if(f.getName().equals("dklb")){
                            if(f.get(dataList.get(i))!=null) {
                                value = systemDictCacheService.findSysDictionaryCode(Constants.Constants_DKLB, f.get(dataList.get(i)).toString(),Constants.DICTIONARY_DESC);
                            }
                        }else if(f.getName().equals("pjzl")){
                            if(f.get(dataList.get(i))!=null) {
                                value = systemDictCacheService.findSysDictionaryCode(Constants.Constants_PJZL, f.get(dataList.get(i)).toString(),Constants.DICTIONARY_DESC);
                            }
                        }else  if(f.getName().equals("cdhdq")){
                            if(f.get(dataList.get(i))!=null) {
                                value = systemDictCacheService.findSysDictionaryCode(Constants.Constants_CDHDQ, f.get(dataList.get(i)).toString(),Constants.DICTIONARY_DESC);
                            }
                        }else if(f.getName().equals("dbbz") || f.getName().equals("dbywzl")){
                            if(f.get(dataList.get(i))!=null){
                                value=systemDictCacheService.findSysDictionaryCode(Constants.Constants_DBFS,f.get(dataList.get(i)).toString(),Constants.DICTIONARY_DESC);
                            }
                        }else{
                            value = f.get(dataList.get(i)) + "";
                        }
                        if (value!=null && !value.equals("null") && !value.equals("")) {
                            row.createCell(j).setCellValue(value);
                        } else {
                            row.createCell(j).setCellValue("");
                        }
                    }
                }
            }

            FileOutputStream fout = new FileOutputStream(filePath);
            wb.write(fout);
            fout.close();
        } catch (IOException e) {
            e.printStackTrace();
            fileName = "error";
            flag=false;
        } catch (Exception e) {
            e.printStackTrace();
            fileName = "error";
            flag=false;
        } finally {

        }
        logsService.handleBuzLogData(userIp,"logs.type."+type,"logs.operation.exportExcel",flag,ResourceUtils.getLocaleString("logs."+type+".export"));
        return fileName;
    }
}
